<?php
/**
 * Created by PhpStorm.
 * User: 李壮壮
 * Date: 2020-3-27
 * Time: 11:30
 */

namespace App\Plugin;

use AlibabaCloud\Client\AlibabaCloud;
use Illuminate\Support\Facades\Http;

/**
 * Class AliSms
 * 短信发送api
 * @package App\Plugin
 */
class AliSms
{

    /**
     * 发送短信
     * @param string $phone
     * @throws \Exception
     */
    public function sendSms(string $phone)
    {
        AlibabaCloud::accessKeyClient('LTAI9QJpzbyKvzD5', '1oURST2yfcYru0dgMZHzAkAg1lrJme')
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $phone,
                        'SignName' => "日照游",
                        'TemplateCode' => "SMS_138155094",
                        'TemplateParam'=>json_encode([
                            'code'=>$this->generateCode($phone)
                        ])
                    ],
                ])
                ->request();
        }catch (\Exception $e) {
            \Log::info($e->getMessage());
        }

    }

    /**
     * 生成验证码
     * @param $phone
     * @return int
     * @throws \Exception
     */
    private function generateCode($phone)
    {
        $code = random_int(100000, 999999);
        $this->StorageCache($phone, $code);
        return $code;
    }

    private function StorageCache($phone, $code)
    {
        cache()->put($phone, $code, now()->addMinutes(5));
    }
}
